//
//  TTMessageViewController.m
//  TaoTuo
//
//  Created by admin on 2019/8/15.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTMessageViewController.h"
#import <JXPagingView/JXPagerView.h>
#import <JXCategoryView.h>
#import "TTJieTuoView.h"
#import "TTZuanshiView.h"
//#import "TTACCView.h"
#import "TTGemstonesView.h"
#import "TTQueryCertificateView.h"

#import "TTSearchInsertModel.h"
#import "TTSearchModel.h"

#import "TTGoodsListViewController.h"

#import "TTDiamondViewController.h"

#import "TTSearchViewController.h"
#import "TTCertificateQueryResultViewController.h"

#import "TTGoodsListViewController.h"

@interface TTMessageViewController ()<JXCategoryViewDelegate, JXCategoryListContainerViewDelegate, JXCategoryListContentViewDelegate>
{
    CGFloat bottomH;
}

@property (nonatomic, strong) JXCategoryTitleView *categoryTitleView;
@property (nonatomic, strong) JXCategoryListContainerView *listContainerView;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) NSMutableArray *listViews;
@property (nonatomic, strong) UIButton *searchBtn;

@property (nonatomic, strong) NSMutableArray *xkArray;  // 镶口
@property (nonatomic, strong) NSMutableArray *scArray;  // 手寸
@property (nonatomic, strong) NSMutableArray *jzArray;  // 金重
@property (nonatomic, strong) NSMutableArray *szArray;  // 手镯内径
@property (nonatomic, strong) NSMutableArray *hotArray;  // 热门搜索

@property (nonatomic, assign) NSInteger curretnIndex;   // 当前index

/// 当前分类
@property (nonatomic, assign) NSInteger currentCategoryIndex;


@property (nonatomic, strong) NSMutableArray *searchTitlesArray;

///当前分类变化了
@property (nonatomic, assign) BOOL currentCategoryIndexChanged;

/// 钻饰上次请求任务
@property (nonatomic, strong) NSURLSessionDataTask *lastZuanshiTask;
/// 裸石上次请求任务
@property (nonatomic, strong) NSURLSessionDataTask *lastLuoshiTask;

@end

@implementation TTMessageViewController

- (UIStatusBarStyle)preferredStatusBarStyle
{
    if (@available(iOS 13.0, *)) {
        return UIStatusBarStyleDarkContent;
    } else {
        return UIStatusBarStyleDefault;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.searchTitlesArray = [NSMutableArray arrayWithObjects:@"搜索", @"搜索", @"搜索", nil];
    self.curretnIndex = 0;
    
    /// 钻石view分类选择改变了
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zuanshiViewCategoryNameChanged:) name:@"zuanshiViewCategoryNameChanged_key" object:nil];
    
    /// 钻饰参数发生变化
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zuanshiParamsChangedNotify:) name:@"zuanshi_chooseItemsChangedNotify_key" object:nil];
    
    /// 裸石参数发生变化
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(luoshiParamsChangedNotify:) name:@"luoshi_chooseItemsChangedNotify_key" object:nil];
    
    bottomH = 62;
    // 加载数据
    [self setupDatas];
    
    [self setupSubviews];
    
    
}

/// 钻石参数发生变化
- (void)zuanshiParamsChangedNotify:(NSNotification *)notify
{
    if (self.curretnIndex != 0) {
        return;
    }
    NSDictionary *dic = notify.object;
    [self getGoodsTotalCountWithParams:dic];
}


/// 钻石view分类选择改变了
- (void)zuanshiViewCategoryNameChanged:(NSNotification *)notify
{
    self.currentCategoryIndex = [notify.object integerValue];

    self.currentCategoryIndexChanged = YES;
    
}

/// 裸石参数发生变化
- (void)luoshiParamsChangedNotify:(NSNotification *)notify
{
    if (self.curretnIndex != 1) {
        return;
    }
    // 裸石
    id<TTSearchViewProtocal> view = self.listViews[1];
    TTGemstonesView *gemView = (TTGemstonesView *)view;
    if (gemView.zlMinTF.text.length == 0) {
        [gemView.resultDic removeObjectForKey:@"param.diaSizeMin"];
    } else {
        gemView.resultDic[@"param.diaSizeMin"] = gemView.zlMinTF.text;
    }
    if (gemView.zlMaxTF.text.length == 0) {
        [gemView.resultDic removeObjectForKey:@"param.diaSizeMax"];
    } else {
        gemView.resultDic[@"param.diaSizeMax"] = gemView.zlMaxTF.text;
    }
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if ([gemView.zsTF.text removeBlank].length > 0) {
        dic[@"param.reportNo"] = [gemView.zsTF.text removeFirstAndLastBlank];
    }
    NSMutableDictionary *paramDic = [gemView.zsTF.text removeBlank].length > 0 ? dic : gemView.resultDic;
    [self getGemstonesCountWithParams:paramDic];
}

- (void)getGemstonesCountWithParams:(NSMutableDictionary *)dic
{
    if (self.lastLuoshiTask.state != NSURLSessionTaskStateCompleted) {
        [self.lastLuoshiTask cancel];
    }
    [dic setObject:@(0) forKey:@"pagenum"];
    [dic setObject:@(1) forKey:@"pagesize"];
    // 降序
    [dic setObject:@1 forKey:@"param.orderFlag"];
    
    @weakify(self)
    self.lastLuoshiTask = [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:diamondDataSearchWholesaler_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        NSString *title = [NSString stringWithFormat:@"搜索(%@粒)", responseObject[@"count"]];
        self.searchTitlesArray[1] = title;
        
        [self setSearchBtnTitle:self.searchTitlesArray[1]];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        
    } showLoadingInView:nil];
}

- (void)setupDatas
{
    // 前两个搜索页面的数据
    NSString *path = [[NSBundle mainBundle] pathForResource:@"search_insert" ofType:@"json"];
    
    NSData *data = [NSData dataWithContentsOfFile:path];
    
    NSError *error = nil;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    
    // 镶口
    for (NSDictionary *mDic in dic[@"insertRange"]) {
        [self.xkArray addObject:[TTSearchInsertModel modelWithJSON:mDic]];
    }
    
    // 手寸
    for (NSDictionary *mDic in dic[@"handInch"]) {
        [self.scArray addObject:[TTSearchInsertModel modelWithJSON:mDic]];
    }
    
    // 金重
    for (NSDictionary *mDic in dic[@"goldenWeight"]) {
        [self.jzArray addObject:[TTSearchInsertModel modelWithJSON:mDic]];
    }
    
    // 手镯内径
    for (NSDictionary *mDic in dic[@"braceletInnerDiameter"]) {
        [self.szArray addObject:[TTSearchInsertModel modelWithJSON:mDic]];
    }
    
    // 热门
    for (NSDictionary *mDic in dic[@"hotSearch"]) {
        [self.hotArray addObject:[TTSearchInsertModel modelWithJSON:mDic]];
    }
    
    
}

- (void)setDiamondParamsModel:(TTShopCartDiamondParamsModel *)diamondParamsModel
{
    _diamondParamsModel = diamondParamsModel;
    self.defaultSelectIndex = 1;
    self.categoryTitleView.defaultSelectedIndex = self.defaultSelectIndex;
    self.listContainerView.defaultSelectedIndex = self.defaultSelectIndex;
    self.curretnIndex = self.defaultSelectIndex;
    
}

- (void)setupSubviews
{
    self.titles = @[@"钻饰", @"钻石", @"查证书"];
    self.categoryTitleView = [[JXCategoryTitleView alloc] initWithFrame:CGRectMake(0, 0, 220, 44)];
    self.categoryTitleView.delegate = self;
    self.categoryTitleView.titles = self.titles;
    [self.view addSubview:self.categoryTitleView];
    self.categoryTitleView.contentEdgeInsetLeft = 20;        // 左边距
    self.categoryTitleView.contentEdgeInsetRight = 20;       // 右边距
    self.categoryTitleView.titleSelectedColor = UIColorHex(333333);
    self.categoryTitleView.titleColor = UIColorHex(333333);
    self.categoryTitleView.titleLabelZoomEnabled = NO;
    
    [self.categoryTitleView removeFromSuperview];
    self.navigationItem.titleView = self.categoryTitleView;
    
    JXCategoryIndicatorLineView *lineView = [[JXCategoryIndicatorLineView alloc] init];
    lineView.indicatorColor = UIColorHex(9B71FF);
    lineView.indicatorHeight = 8;
    lineView.verticalMargin = 10;
    lineView.indicatorCornerRadius = 4;
    lineView.lineStyle = JXCategoryIndicatorLineStyle_Lengthen;
    self.categoryTitleView.indicators = @[lineView];
    
    
    _listContainerView = [[JXCategoryListContainerView alloc] initWithDelegate:self];
    _listContainerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.view.height - StatusBarAndNavBar_Height - bottomH - Tabbar_Bottom_height);
    [self.view addSubview:_listContainerView];
    
    self.categoryTitleView.contentScrollView = self.listContainerView.scrollView;
    
    
    if (self.listViews.count == 0) {
        TTZuanshiView *zsView = [[TTZuanshiView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.listContainerView.height)];
        [self.listViews addObject:zsView];
        
        TTGemstonesView *gemView = [[TTGemstonesView alloc] initWithFrame:zsView.frame];
        gemView.diamodParamsModel = self.diamondParamsModel;
        [self.listViews addObject:gemView];
        
        TTQueryCertificateView *queryView = [[TTQueryCertificateView alloc] initWithFrame:zsView.frame];
        [self.listViews addObject:queryView];
        
        
        
    }
    
    UIButton *resetBtn = [UIButton createButtonWithTitle:@"重置" titleColor:UIColorHex(#333333) titleFontSize:16 borderColor:UIColorHex(#808080) cornerRadius:20 contentEdgeInsets:UIEdgeInsetsZero target:self action:@selector(resetBtnClick)];
    resetBtn.frame = CGRectMake(12, _listContainerView.bottom + 11, 88, 40);
    [self.view addSubview:resetBtn];
    
    UIButton *searchBtn = [UIButton createButtonWithTitle:@"" titleColor:UIColor.whiteColor titleFontSize:14 borderColor:UIColorHex(#808080) cornerRadius:20 contentEdgeInsets:UIEdgeInsetsZero target:self action:@selector(searchBtnClick)];
    searchBtn.backgroundColor = UIColorHex(#8B57E6);
    searchBtn.frame = CGRectMake(resetBtn.right + 15, resetBtn.top, self.view.width - resetBtn.right - 27, 40);
    searchBtn.isNeedLogin = YES;
    [self.view addSubview:searchBtn];
    self.searchBtn = searchBtn;
    
    [self setSearchBtnTitle:@"搜索"];
    
    
    self.categoryTitleView.defaultSelectedIndex = self.defaultSelectIndex;
    self.listContainerView.defaultSelectedIndex = self.defaultSelectIndex;
    self.curretnIndex = self.defaultSelectIndex;
    
}

- (void)setSearchBtnTitle:(NSString *)title
{
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:title];
    [attr addAttribute:NSForegroundColorAttributeName value:UIColor.whiteColor range:[title rangeOfAll]];
    [attr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:17] range:[attr.string rangeOfString:@"搜索"]];
    [self.searchBtn setAttributedTitle:attr forState:UIControlStateNormal];
}

// 跳转到搜索页面
- (void)gotoSearchViewController
{
//    TTSearchViewController *searchVC = [[TTSearchViewController alloc] init];
//    searchVC.hotArray = self.hotArray;
//    [self.navigationController pushViewController:searchVC animated:YES];
}

// 重置
- (void)resetBtnClick
{
    id<TTSearchViewProtocal> view = self.listViews[self.curretnIndex];
    [view resetView];
    
}


// 跳转到搜索结果
- (void)gotoShowSearchResultWithDic:(NSDictionary *)dic searchDic:(NSMutableDictionary *)searchDic
{
    NSString *searchName = @"";
    NSArray *keys = [searchDic.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSString * _Nonnull obj1, NSString *  _Nonnull obj2) {
        return obj1.intValue > obj2.intValue;
    }];
    for (NSString *key in keys) {
        NSString *value = searchDic[key];
        if (value.length > 0) {
            searchName = [searchName stringByAppendingString:[NSString stringWithFormat:@"%@ ", searchDic[key]]];
        }
    }
    TTGoodsListViewController *goodsVC = [[TTGoodsListViewController alloc] initWithSearchName:searchName paramsDic:dic selectIndex:self.currentCategoryIndex];
    [self.navigationController pushViewController:goodsVC animated:YES];
}

- (void)getGoodsTotalCountWithParams:(NSDictionary *)param
{
    if (self.lastZuanshiTask.state != NSURLSessionTaskStateCompleted) {
        [self.lastZuanshiTask cancel];
    }
    NSMutableDictionary *dic = param.mutableCopy;
    [dic setObject:@(1) forKey:@"param.pageIndex"];
    [dic setObject:@(1) forKey:@"param.pageSize"];
    if (dic[@"param.categoryName"] == nil) {
        dic[@"param.categoryName"] = @"女戒";
    }
    @weakify(self)
    self.lastZuanshiTask = [[LLNetworkManagerTool sharedManager] postUrlString:queryList_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        NSString *title = [NSString stringWithFormat:@"搜索(%@款)", responseObject[@"TotalCount"]];
        self.searchTitlesArray[0] = title;
        if (self.curretnIndex == 0) {
            [self setSearchBtnTitle:self.searchTitlesArray[0]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    } showLoadingInView:nil];
    
}


// 搜索
- (void)searchBtnClick
{
    id<TTSearchViewProtocal> view = self.listViews[self.curretnIndex];
    if (self.curretnIndex == 0) {
        TTZuanshiView *zsView = (TTZuanshiView *)view;
        NSDictionary *dic = [zsView getParamsDic];
        [self gotoShowSearchResultWithDic:dic searchDic:zsView.rightView.searchNameDic];
        
    } else if (self.curretnIndex == 1) {
        // 裸石
        TTGemstonesView *gemView = (TTGemstonesView *)view;
        if (gemView.zlMinTF.text.length == 0) {
            [gemView.resultDic removeObjectForKey:@"param.diaSizeMin"];
        } else {
            gemView.resultDic[@"param.diaSizeMin"] = gemView.zlMinTF.text;
        }
        if (gemView.zlMaxTF.text.length == 0) {
            [gemView.resultDic removeObjectForKey:@"param.diaSizeMax"];
        } else {
            gemView.resultDic[@"param.diaSizeMax"] = gemView.zlMaxTF.text;
        }
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        if ([gemView.zsTF.text removeBlank].length > 0) {
            dic[@"param.reportNo"] = [gemView.zsTF.text removeFirstAndLastBlank];
        }
        
        TTDiamondViewController *diamondVC = [[TTDiamondViewController alloc] init];
        diamondVC.paramsDic = [gemView.zsTF.text removeBlank].length > 0 ? dic : gemView.resultDic;
        [self.navigationController pushViewController:diamondVC animated:YES];
        
    } else if (self.curretnIndex == 2) {
        // 证书查询
        TTQueryCertificateView *queryView = (TTQueryCertificateView *)view;
        NSString *certNo = [queryView.textField.text removeFirstAndLastBlank];
        if (certNo.length == 0) {
            [self.view makeToast:@"请输入证书号"];
            return;
        }
        TTCertificateQueryResultViewController *vc = [[TTCertificateQueryResultViewController alloc] initWithCertNo:certNo];
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    
    
}

#pragma mark - JXCategoryViewDelegate
- (void)categoryView:(JXCategoryBaseView *)categoryView didScrollSelectedItemAtIndex:(NSInteger)index {
    //    NSLog(@"%@", NSStringFromSelector(_cmd));
    self.curretnIndex = index;
    
    [self setSearchBtnTitle:self.searchTitlesArray[index]];
}

- (void)categoryView:(JXCategoryBaseView *)categoryView didClickSelectedItemAtIndex:(NSInteger)index {
    self.curretnIndex = index;
    [self.listContainerView didClickSelectedItemAtIndex:index];
    
    [self setSearchBtnTitle:self.searchTitlesArray[index]];
}

- (void)categoryView:(JXCategoryBaseView *)categoryView scrollingFromLeftIndex:(NSInteger)leftIndex toRightIndex:(NSInteger)rightIndex ratio:(CGFloat)ratio {
    [self.listContainerView scrollingFromLeftIndex:leftIndex toRightIndex:rightIndex ratio:ratio selectedIndex:categoryView.selectedIndex];
}

#pragma mark - JXCategoryListContainerViewDelegate

- (id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index {
    id<JXCategoryListContentViewDelegate> listView = (id<JXCategoryListContentViewDelegate>)self.listViews[index];
    
    if (index == 0) {
    } else if (index == 1) {
        TTGemstonesView *gemView = (TTGemstonesView *)listView;
        [gemView parseData];
    }
    
    return listView;
}

- (NSInteger)numberOfListsInlistContainerView:(JXCategoryListContainerView *)listContainerView {
    return self.titles.count;
}


- (UIView *)listView
{
    return self.view;
}

- (void)backAction
{
    if (self.isPresent) {
        [self dismissViewControllerAnimated:NO completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (NSMutableArray *)listViews
{
    if (!_listViews) {
        _listViews = [NSMutableArray array];
    }
    return _listViews;
}

- (NSMutableArray *)xkArray
{
    if (!_xkArray) {
        _xkArray = [NSMutableArray array];
    }
    return _xkArray;
}

- (NSMutableArray *)scArray
{
    if (!_scArray) {
        _scArray = [NSMutableArray array];
    }
    return _scArray;
}

- (NSMutableArray *)jzArray
{
    if (!_jzArray) {
        _jzArray = [NSMutableArray array];
    }
    return _jzArray;
}

- (NSMutableArray *)szArray
{
    if (!_szArray) {
        _szArray = [NSMutableArray array];
    }
    return _szArray;
}

- (NSMutableArray *)hotArray
{
    if (!_hotArray) {
        _hotArray = [NSMutableArray array];
    }
    return _hotArray;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"[< %@ >] ---> 释放了", self.className);
}

@end
